import { defineStore } from 'pinia';
import { Dish } from '@/types/dish';

export const useHomeStore = defineStore('home', {
    state: () => ({
        menu: [],
        cart: [] as { dish: Dish; quantity: number; standards?: { [key: string]: string } }[]
    }),
    persist: true,
    actions: {
        addToCart(dish: Dish, quantity: number, standards?: { [key: string]: string }) {
            const existingItem = this.cart.find((item) => item.dish.id === dish.id);
            if (existingItem) {
                existingItem.quantity += quantity;
            } else {
                this.cart.push({ dish, quantity, standards });
            }
        },
        removeFromCart(dishId: string) {
            this.cart = this.cart.filter((item) => item.dish.id !== dishId);
        },
        clearCart() {
            this.cart = []
        },
        updateQuantity(dishId: string, quantity: number) {
            const item = this.cart.find((item) => item.dish.id === dishId);
            if (item) {
                item.quantity = quantity;
            }
        }
    },
    getters: {
        cartTotal: (state) => {
            return state.cart.reduce((total, item) => total + item.quantity * item.dish.price, 0);
        },
        cartItemCount: (state) => {
            return state.cart.reduce((total, item) => total + item.quantity, 0);
        }
    }
});
